package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.common.constant.MessageConstant;
import com.atguigu.common.constant.RedisMessageConstant;
import com.atguigu.common.entity.Result;
import com.atguigu.common.exception.OrderReservationsException;
import com.atguigu.pojo.Order;
import com.atguigu.service.OrderInfoService;
import com.atguigu.vo.OrderVo;
import javafx.scene.control.TableRow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    JedisPool jedisPool;

    @Reference
    OrderInfoService orderInfoService;

    //提交预约
    @PostMapping("/submitReservation")
    public Result submitReservation(@RequestBody OrderVo orderVo){
        Jedis jedis = jedisPool.getResource();
        //判断验证码是否正确
        String code = orderVo.getValidateCode();
        String telephone = orderVo.getTelephone();
        String s = jedis.get(RedisMessageConstant.SENDTYPE_ORDER +":"+telephone);
        if (s==null){
            return new Result(false,"验证码过期，请求重新发送");
        }
        String redisCode = s.split("_")[0];
        if (!(code!=null&&code.equals(redisCode))){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //提交预约
        try {
            Order order = orderInfoService.submitReservation(orderVo);
            return new Result(true,MessageConstant.ORDERSETTING_SUCCESS);
        } catch (OrderReservationsException e) {
            return new Result(false,e.getMessage());
        } catch (Exception e) {
            return new Result(false,MessageConstant.ORDER_FAIL);
        }
    }

    @GetMapping("/findById")
    public Result findById(@RequestParam("orderId")Integer id){
        Order order = orderInfoService.findById(id);
        return new Result(true,MessageConstant.ORDERSETTING_SUCCESS,order);
    }
}
